/**
 * 
 */
package com.pj.logback;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import ch.qos.logback.classic.net.SocketAppender;

/**
 * @author jigq
 *
 * @date 2022年9月14日
 */
public class CustemSocketAppender extends SocketAppender {

	private final static Logger logger = LoggerFactory.getLogger(CustemSocketAppender.class);

	private final static String NAME_ETH0 = "eth0";

	private static String os_name;
	
	private boolean enabled=true;

	public CustemSocketAppender() {
		try {
			os_name = System.getProperty("os.name").toLowerCase();
			if (isLinux()) {
				getLinuxIpAddress();
			}
			if (isWindows()) {
				getWindowsIpAddress();
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	
	@Override
	public void start() {
		if(enabled){
			super.start();
		}
	}


	/**
	 * @throws UnknownHostException
	 */
	private void getWindowsIpAddress() throws UnknownHostException {
		InetAddress address = InetAddress.getLocalHost();
		MDC.put("ip", address.getHostAddress());
	}

	/**
	 * @throws SocketException
	 */
	private void getLinuxIpAddress() throws SocketException {
		Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
		while (en.hasMoreElements()) {
			NetworkInterface netInterface = en.nextElement();
			String name = netInterface.getName();
			if (name.equals(NAME_ETH0)) {
				Enumeration<InetAddress> inetAddresses = netInterface.getInetAddresses();
				while (inetAddresses.hasMoreElements()) {
					InetAddress ip = inetAddresses.nextElement();
					logger.info("ip:{}", ip.getHostAddress());
					MDC.put("ip", ip.getHostAddress());
				}
			}
		}
	}

	private static boolean isLinux() {
		return os_name.indexOf("linux") >= 0;
	}

	private static boolean isWindows() {
		return os_name.indexOf("windows") >= 0;
	}
}
